package com.xjd.transport.mock;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ReceiveSocketServer extends Thread {
	public static Logger log = LoggerFactory.getLogger(ReceiveSocketServer.class);

	int port;
	boolean success = false;
	boolean failed = false;
	ByteArrayOutputStream bufOut = new ByteArrayOutputStream();

	public void setPort(int port) {
		this.port = port;
	}
	
	public boolean isSuccess() {
		return success;
	}
	
	public boolean isFailed() {
		return failed;
	}
	
	public byte[] getReceivedBytes() {
		return bufOut.toByteArray();
	}
	
	public void run() {
		try {
			serve();
		} catch (IOException e) {
			log.error("server error", e);
			failed = true;
		}
	}

	public void serve() throws IOException {
		ServerSocket server = new ServerSocket(port);

		Socket socket = server.accept();
		InputStream in = socket.getInputStream();

		int i = 0;
		long totall = 0;
		while ((i = in.read()) != -1) {
			bufOut.write(i);
			log.trace("read " + " : " + i + "\t[" + (++totall) + "]");
		}
		success = true;

		try {
			socket.close();
			server.close();
		} catch (Exception e) {
			log.error("server error", e);
		}
	}

	public static void main(String[] args) throws IOException {
		ReceiveSocketServer s = new ReceiveSocketServer();
		s.setPort(9090);
		s.run();
	}

}
